package com.neusoft.tmall.ums.controller;

import com.google.common.collect.Maps;
import com.neusoft.tmall.ums.entity.UmsMenu;
import com.neusoft.tmall.ums.entity.UmsMenuExample;
import com.neusoft.tmall.ums.service.UmsMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("admin")
public class UmsMenuController {
   @Autowired
    private UmsMenuService umsMenuService;

   //获取菜单管理数据
    @GetMapping("info")
    public Object getMenu() throws IllegalAccessException {
        UmsMenuExample umsMenuExample = new UmsMenuExample();
        List<UmsMenu> list = umsMenuService.selectByExample(umsMenuExample);
        if(list == null || list.size() == 0){
            System.out.println("菜单数据查询失败");
        }
        for (UmsMenu umsMenu: list){
            System.out.println(umsMenu);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        System.out.println(authentication.getPrincipal().getClass());
        //通过反射机制获取所登陆用户的用户名
        Object obj  = authentication.getPrincipal();
        Class class1 = obj.getClass();
        Field[] fields = class1.getDeclaredFields();
        fields[0].setAccessible(true);
        Object obj1 = fields[0].get(obj);
        System.out.println("登录的UmsAdmin为："+obj1);
        Class class2 = obj1.getClass();
        Field[] fields1 = class2.getDeclaredFields();
        fields1[1].setAccessible(true);
        fields1[3].setAccessible(true);
        String username = (String) fields1[1].get(obj1);
        String icon = (String) fields1[3].get(obj1);
        System.out.println("username值为："+username);
        System.out.println("icon值为："+icon);
        Map<String, Object> map = Maps.newHashMap();
        map.put("menus",list);
        map.put("icon",icon);
        map.put("username",username);
        return map;
    }
}
